package com.qf.interceptor;

import com.qf.bean.User;
import com.qf.constant.SSMConstant;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author yao
 */
public class AuthenInterceptor implements HandlerInterceptor {



    // 1.拦截器的前处理.   请求到达前端控制器之前.
    @Override
    public boolean preHandle(
                            HttpServletRequest request,
                            HttpServletResponse response,
                            Object handler) throws Exception {

        //1. 获得session对象.
        HttpSession session = request.getSession();

        //2. 从session域中获取用户信息.
        User user = (User) session.getAttribute(SSMConstant.USER);

        //3. 判断用户是否登录
        if (user != null) {
            // -> 登录了,放行.
            return true;
        } else{
        // -> 未登录,拦截并重定向到登录页面.
            response.sendRedirect(request.getContextPath() + "/user/login");
            return false;
        }
    }

    // 2.渲染视图之前.
    @Override
    public void postHandle(
                        HttpServletRequest request,
                        HttpServletResponse response,
                        Object handler,
                        ModelAndView modelAndView) throws Exception {

        // 给modelAndView添加或修改数据.
        System.out.println("渲染视图之前...");
    }

    // 3.响应数据之前处理.
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        // 粗粒度查看访问量.
        // 记录日志.
        System.out.println("响应数据之前...");
    }
}
